package com.lijianlove.message.dal;

import com.lijianlove.message.common.enums.MsgStatusEnum;
import com.lijianlove.message.common.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author lijian
 * @date 2019/5/29 下午5:37
 */
@Slf4j
@Service
public class MessageStoreServiceImpl implements MessageStoreService {


    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public Message get(String msgId) {
        log.info("MessageStoreServiceImpl.get {}", msgId);
        Message message = jdbcTemplate.queryForObject("select * from message where id='" + msgId + "'", getMessageRowMapper());
        return message;
    }

    @Override
    public String save(Message msg) {
        log.info("MessageStoreServiceImpl.save {}", msg);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jdbcTemplate.execute("insert into message values ('" + msg.getId() + "','" + format.format(msg.getCreateTime()) + "','" + format.format(msg.getExpireTime()) + "','" + msg.getBody() + "','" + msg.getUniquMetaKey() + "'," + msg.getStatus().getValue() + ")");
        return null;
    }

    @Override
    public void updateStatus(Message message) {
        log.info("MessageStoreServiceImpl.updateStatus {}", message);
        jdbcTemplate.execute("update message set status=" + message.getStatus().getValue() + " where id='" + message.getId() + "'");
    }

    @Override
    public List<Message> listByStatus(MsgStatusEnum status) {
        List<Message> messages = jdbcTemplate.query("select * from message where status=" + status.getValue() + " and expire_time>now() order by id desc", getMessageRowMapper());
        return messages;
    }

    private RowMapper<Message> getMessageRowMapper() {
        return (resultSet, i) -> {
            Message msg = new Message();
            msg.setId(resultSet.getString("id"));
            msg.setExpireTime(resultSet.getDate("expire_time"));
            msg.setCreateTime(resultSet.getDate("create_time"));
            msg.setUniquMetaKey(resultSet.getString("unique_meta_key"));
            msg.setBody(resultSet.getString("body"));
            msg.setStatus(MsgStatusEnum.getByValue(resultSet.getInt("status")));
            return msg;
        };
    }
}
